package com.qzimp.fujiancuo.controller.api;


import com.qzimp.fujiancuo.entity.Userinfo;
import com.qzimp.fujiancuo.entity.dto.UserinfoLoginDto;
import com.qzimp.fujiancuo.entity.dto.UserinfoRegisterDto;
import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.entity.vo.ResultVo;
import com.qzimp.fujiancuo.exceptions.ApiException;
import com.qzimp.fujiancuo.service.UserinfoService;
import com.qzimp.fujiancuo.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserinfoApi {
    private UserinfoService userinfoService;

    @Autowired
    public UserinfoApi(UserinfoService userinfoService) {
        this.userinfoService=userinfoService;

    }
    @PostMapping("/userinfo/login")
    public ResultVo login(@Validated @RequestBody UserinfoLoginDto userinfoLoginDto){
        Userinfo userinfo=userinfoService.findUserinfoByLoginName(userinfoLoginDto.getLoginName());

        String md5Password= StringUtil.MD5(userinfoLoginDto.getPassword()+userinfo.getSalt());
        userinfo=userinfoService.login(userinfoLoginDto.getLoginName(),md5Password);
       if(userinfo==null){
           throw new ApiException(ResultCode.USER_LOGIN_ERROR);
       }
        return  new ResultVo(ResultCode.SUCCESS,userinfo);
    }
    @PostMapping("/userinfo/register")
    public ResultVo register(@Validated @RequestBody UserinfoRegisterDto userinfoRegisterDto){
            //注册时，要先判断账号是否重复
            String loginName=userinfoRegisterDto.getLoginName();
            Userinfo userinfo= userinfoService.findUserinfoByLoginName(loginName);

            if(userinfo!=null){
                return ResultVo.error(ResultCode.LOGIN_NAME_IS_REPEAT);
            }
            //获取6位数 salt
            String six= StringUtil.generateSixCharString(6);
            userinfo=new Userinfo();
            String md5=StringUtil.MD5(userinfoRegisterDto.getPassword()+six);

            BeanUtils.copyProperties(userinfoRegisterDto,userinfo);
            userinfo.setSalt(six);
            userinfo.setPassword(md5);
            try {
                userinfoService.save(userinfo);
            }catch (Exception e){

                throw new ApiException(ResultCode.USER_REGISTER_FAILURE);
            }

            return  new ResultVo(ResultCode.USER_REGISTER_OK);
    }


    @GetMapping("/userinfo/forgetpassword")
    public  boolean forgetPassword(){

        return  true;

    }



}
